//////////////////////////////////////////////////////////////////////////
/// Copyright (c) 2011, Sidorenko 'PC' Alexander                       ///
/// mailto: sidorenko /*dot*/ alexander (at) gmail [dot] com           ///
/// This file is a part of the Radiating Gas Dynamics project          ///
//////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Problem.h"

#include "SodProblem.h"
#include "SodProblem2D.h"
#include "BrickProblem.h"

#ifdef _PROFILE
#include "Timer.h"

TimingsList g_zeroRatesTimings;
TimingsList g_normalizeRatesTimings;
TimingsList g_updateRatesTimings;
TimingsList g_evaluateStepTimings;
TimingsList g_applyRatesTimings;
TimingsList g_updateStatesTimings;
TimingsList g_findMinMaxTimings;
TimingsList g_totalWorkerTimings;
TimingsList g_totalParentTimings;

void printTimings(FILE *file, const TimingsList &lst, const char* name)
{
	fprintf(file, "Most recent timings for %s:\n", name);
	for (unsigned int i = 0; i < MaxNumberOfTimings; ++i)
		fprintf(file, "%f\n", lst.getTiming(i));
	fprintf(file, "Average is: %f\n", lst.getAverage());
}

void dumpTimings()
{
	FILE* f = fopen("C:\\Users\\Alexander\\Desktop\\timings.txt", "wt");

	printTimings(f, g_zeroRatesTimings, "zero rates");
	fprintf(f, "\n");

	printTimings(f, g_normalizeRatesTimings, "normalize rates");
	fprintf(f, "\n");

	printTimings(f, g_updateRatesTimings, "update rates");
	fprintf(f, "\n");

	printTimings(f, g_evaluateStepTimings, "evaluate step");
	fprintf(f, "\n");

	printTimings(f, g_applyRatesTimings, "apply rates");
	fprintf(f, "\n");

	printTimings(f, g_updateStatesTimings, "update states");
	fprintf(f, "\n");

	printTimings(f, g_findMinMaxTimings, "find min max");
	fprintf(f, "\n");

	printTimings(f, g_totalWorkerTimings, "worker total");
	fprintf(f, "\n");

	printTimings(f, g_totalParentTimings, "parent total");
	fprintf(f, "\n");

	fclose(f);
}
#endif

unsigned int appliedTimes = 0;

Problem* Problem::readProblem(std::string fileName)
{
	FILE* f = fopen(fileName.c_str(), "rb");

	if (NULL == f)
		return NULL;

	Type type = UNKNOWN;

	fread(&type, sizeof(type), 1, f);

	fclose(f);

	Problem *p = NULL;

	switch(type)
	{
		case SODS_SHOCK_TUBE:
			p = new SodProblem(gdScalar(1.4), gdScalar(0.5), 8, FALSE);
		break;

		case BRICK_2D:
			p = new BrickProblem(gdScalar(1.4), gdScalar(0.5), 8, FALSE);
		break;

		case SOD_2D:
			p = new SodProblem2d(gdScalar(1.4), gdScalar(0.5), 8, FALSE);
		break;

		case UNKNOWN:
		default:
			p = NULL;
		break;
	}

	if (NULL != p)
	{
		if (!p->openFile(fileName))
		{
			delete p;
			p = NULL;
		}
	}

	return p;
}
